﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DeviceNotificationAdapter.cs" company="Matthias Friedrich">
//   Copyright © Matthias Friedrich 2009
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace DeviceManagement
{
	using System;
	using System.Collections.Generic;
	using System.ComponentModel;
	using System.ComponentModel.Design;
	using System.Drawing;
	using System.Windows.Forms;

	[ProvideProperty("ReceiveNotifications", typeof(Control))]
	[ToolboxBitmap(typeof(DeviceNotificationAdapter), "Ressources.event.ico")]
	[Designer(typeof(DeviceNotificationDesigner), typeof(IDesigner))]
	public class DeviceNotificationAdapter : ExtenderProvider<Control>, IComponent
	{
		private static readonly object DisposedEvent = new object();

		private static readonly object ReceiveNotificationsProperty = new object();

		private static readonly object IsRegisteredProperty = new object();

		private readonly EventHandlerList eventHandlers = new EventHandlerList();

		private readonly IDictionary<object, object> extendees = new Dictionary<object, object>();

		private readonly DeviceNotification notification = new DeviceNotification();

		public DeviceNotificationAdapter()
			: base()
		{
		}

		[DefaultValue(true)]
		public bool GetReceiveNotifications(Control control)
		{
			return this.GetProperty<bool>(control, ReceiveNotificationsProperty);
		}

		public void SetReceiveNotifications(Control control, bool value)
		{
			this.SetProperty(control, ReceiveNotificationsProperty, value);

			if (value && !this.GetProperty<bool>(control, IsRegisteredProperty))
			{
				control.HandleCreated += (sender, e) => this.RegisterNotificationForExtendee((Control)sender);
			}

			this.extendees[control] = value;
		}

		private void RegisterNotificationForExtendee(Control control)
		{
			this.notification.Register(DeviceType.Interface);
			this.SetProperty(control, IsRegisteredProperty, true);
		}

		#region IComponent Members

		event EventHandler IComponent.Disposed
		{
			add
			{
				this.eventHandlers.AddHandler(DisposedEvent, value);
			}

			remove
			{
				this.eventHandlers.RemoveHandler(DisposedEvent, value);
			}
		}

		ISite IComponent.Site { get; set; }

		#endregion

		#region IDisposable Members

		void IDisposable.Dispose()
		{
			this.Dispose(true);
		}

		protected bool Disposed { get; private set; }

		protected virtual void Dispose(bool disposing)
		{
			if (disposing && !this.Disposed)
			{
				this.Disposed = true;
			}
		}

		~DeviceNotificationAdapter()
		{
			this.Dispose(false);
			GC.SuppressFinalize(this);
		}

		#endregion
	}
}